package com.pjmike.netty.client;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author pjmike
 * @create 2018-10-24 16:31
 */
@Component
@Slf4j
public class NettyClient  {
    private EventLoopGroup group = new NioEventLoopGroup();
    @Value("${netty.remote.port}")
    private int port;
    @Value("${netty.remote.host}")
    private String host;
    private SocketChannel socketChannel;
//    public void sendMsg(String message) {
//        socketChannel.writeAndFlush(message);
//    }
public void sendMsg(String message,String host,int port) {
       this.start(message,host,port);
   }
//   @PostConstruct
public void start(String message,String host,int port)  {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(host, port)
                .option(ChannelOption.SO_KEEPALIVE, false)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ClientHandlerInitilizer());
        ChannelFuture future = bootstrap.connect();
        socketChannel = (SocketChannel) future.channel();
        //客户端断线重连逻辑

        future.addListener((ChannelFutureListener) future1 -> {
            if (future1.isSuccess()) {
                log.info("连接远程服务端成功");
                socketChannel.writeAndFlush(message);
                log.info("发送报文 {} 成功",message);
                log.info("关闭通道成功");
            } else {
                log.info("成功断开远程服务端");

//                log.info("连接失败，进行断线重连");
//                future1.channel().eventLoop().schedule(() -> start(), 20, TimeUnit.SECONDS);
            }
            this.closeChannel();
        });

    }
    private void closeChannel()
    {
        try{
            if(socketChannel!=null)
            {
                socketChannel.close();
                socketChannel.eventLoop().shutdownGracefully();


            }
        }catch (Exception e)
        {
            log.error(e.getMessage());
        }finally {
            socketChannel = null;
        }
    }
}
